package org.dromara.oce.domain.req;

import com.bytedance.ads.model.*;
import jakarta.validation.constraints.*;
import lombok.Data;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @desc: https://open.oceanengine.com/labels/34/docs/1757798123491403?origin=left_nav
 * @author: cx
 * @date：2025/6/5 10:11
 */
@Data
public class CreateProjectPromotionQo {
    /**
     * 管家账号id
     */
    @NotNull(message = "请选择管家账号")
    private Long accountId;
    /**
     * 广告主id
     */
    @NotEmpty(message = "广告主id不能为空")
    private List<Long> advertiserIds;


    /**
     * 项目数量
     */
    @NotNull(message = "请输入创建项目数量")
    @Min(value = 1, message = "创建项目不能小于1")
    @Max(value = 30, message = "创建项目不能超过30")
    private Integer projectNum;
    /**
     * 项目id
     */
    private Long projectId;
    /**
     * 项目参数
     */
    @NotNull(message = "项目信息不全")
    private ProjectCreateV30Request2 project;


    /**
     * 广告数量
     */
//    @Min(value = 1, message = "广告数量不能小于1")
//    @Max(value = 100,message = "广告数量不能超过30")
    private Integer promotionNum = 1;
    /**
     * 规则配置-广告生成规则  1按创意组数   2按创意组*标题包  3指定数量
     */
    @NotNull(message = "请选择广告生成规则")
    private Integer projectAdRule;
    /**
     * 广告参数
     */
    @NotNull(message = "广告信息不全")
    private CreatePromotionV3Request promotion;


    /**
     * 小程序类型，仅当landing_type = MICRO_GAME 时有效且必填，允许值：
     * WECHAT_GAME 微信小游戏
     * WECHAT_APP微信小程序
     * BYTE_GAME字节小游戏
     * BYTE_APP字节小程序
     * AWEME抖音号
     */
    private String microPromotionType;
    /**
     * 小程序投放载体
     */
    private List<MicroAppInstanceReq> microAppInstanceList;


    /**
     * 素材-多账户分配规则
     * 1 全账户复用
     * 2 平均分配
     * 3 分账户选择
     */
    @NotBlank(message = "请选择素材多账户分配规则")
    private String materialType;
    /**
     * 创意组对象
     */
    @NotEmpty(message = "创意组不能为空")
    List<CreatePromotionGroupQo> groupQos;

    /**
     * 标题包分配方式  1全账户复用    2平均分配  3分账户选择
     */
    @NotBlank(message = "请选择标题包多账户分配规则")
    private String titleWay;
    /**
     * 标题包数组
     */
    @NotEmpty(message = "请选择标题包")
    List<CreateTitleWrapQo> titleWrap;


    /**
     * 字节小程序链接
     */
    private List<CreatePromotionUrlQo> urls;


    /**
     * 落地页分配方式 1全部相同    2按账户分配  3按项目分配   4按广告分配
     */
    private String siteWay;
    /**
     * 微信落地页、短剧专辑链接（抖音号）、字节备用落地页
     */
    @NotEmpty(message = "请选择落地页")
    private List<CreatePromotionUrlQo> externalUrlMaterialList;


    /**
     * 锚点列表
     */
    private List<AnchorMaterialReq> anchorMaterialList;


    public void checkParam() {
        if (ObjectUtils.isEmpty(accountId)) {
            throw new ServiceException("管家账号id不能为空");
        }
        if (ObjectUtils.isEmpty(advertiserIds) || advertiserIds.size() == 0) {
            throw new ServiceException("广告主id不能为空");
        }
        if (1 == this.projectAdRule && this.groupQos.size() > 100) {
            throw new ServiceException("广告数不能大于100（创意组数量 > 100）");
        } else if (2 == this.projectAdRule && this.groupQos.size() * this.titleWrap.size() > 100) {
            throw new ServiceException("广告数不能大于100（创意组数量 * 标题包数量 > 100）");
        } else if (3 == this.projectAdRule && this.promotionNum > 100) {
            throw new ServiceException("广告数不能大于100");
        }
        if (this.project.getRelatedProduct().getProductId() == null) {
            this.project.getRelatedProduct().setProductSetting(ProjectCreateV30RelatedProductProductSetting.NO_MAP);
        } else {
            this.project.getRelatedProduct().setProductSetting(ProjectCreateV30RelatedProductProductSetting.SINGLE);
        }

        //选择已有项目时，项目数量设置为1
        if (!ObjectUtils.isEmpty(this.projectId)) {
            this.projectNum = 1;
            if (this.advertiserIds.size() > 1) {
                throw new ServiceException("选择已有项目创建不支持多账号");
            }
        }


        if ("3".equals(this.materialType)) {
            for (Long advertiserId : this.advertiserIds) {
                Optional<CreatePromotionGroupQo> first = this.groupQos.stream().findFirst();
                if (first.isEmpty()) {
                    throw new ServiceException("广告主：" + advertiserId + "没有上传素材");
                }
            }
        }

        //手动投放
        if (ProjectCreateV30DeliveryMode.MANUAL.equals(this.project.getDeliveryMode())) {
            if (!ObjectUtils.isEmpty(this.project.getDeliveryRange())) {
                if (ProjectCreateV30DeliveryRangeInventoryCatalog.UNIVERSAL_SMART.equals(this.project.getDeliveryRange().getInventoryCatalog())) {
                    //通投智选
                    this.project.getDeliveryRange().setInventoryCatalog(null);
                    this.project.getDeliveryRange().setInventoryType(null);
                } else {
                    this.project.getDeliveryRange().setInventoryType(Arrays.asList("INVENTORY_AWEME_FEED"));
                }
            }
        }else if (ProjectCreateV30DeliveryMode.PROCEDURAL.equals(this.project.getDeliveryMode())) {
            //自动投放没有下面参数
            this.project.setSearchBidRatio(null);
            this.project.setAudienceExtend(null);
            this.promotion.setBudget(null);
            this.promotion.setCpaBid(null);
        }


        if (ObjectUtils.isEmpty(this.project.getMicroPromotionType())) {
            throw new ServiceException("请选择小程序投放载体");
        }
        //小程序投放载体
        if (isWechat() || isByte()) {
            if (ObjectUtils.isEmpty(this.microAppInstanceList) || this.getMicroAppInstanceList().size() == 0) {
                throw new ServiceException("请先选择项目 -> 投放载体 -> 小程序");
            }
            for (MicroAppInstanceReq microAppInstanceReq : this.microAppInstanceList) {
                if (ObjectUtils.isEmpty(microAppInstanceReq.getMicroAppInstanceId())) {
                    throw new ServiceException("项目 -> 投放载体 -> 小程序资产id不能为空");
                }
                if (isByte() && ObjectUtils.isEmpty(microAppInstanceReq.getAssetId())) {
                    throw new ServiceException("项目 -> 投放载体 -> 小程序资产事件不能为空");
                }
            }
        }


        for (CreatePromotionUrlQo urlQo : this.externalUrlMaterialList) {
            if (ObjectUtils.isEmpty(urlQo.getUrl()) || ObjectUtils.isEmpty(urlQo.getAdvertiserId())) {
                throw new ServiceException("落地页信息不全");
            }
        }
        for (CreateTitleWrapQo titleWrapQo : this.titleWrap) {
            if (titleWrapQo.getTitles() == null || titleWrapQo.getTitles().size() == 0) {
                throw new ServiceException("标题包中的标题不能为空");
            }
            for (PromotionCreateV30RequestPromotionMaterialsTitleMaterialListInner title : titleWrapQo.getTitles()) {
                int length = title.getTitle().length();
                if (length > 55 || length < 5) {
                    throw new ServiceException("创意标题，长度为5-55个字, 两个英文字符占1位。");
                }

            }
        }
        for (CreatePromotionGroupQo groupQo : this.groupQos) {
            if (groupQo.getAdvertiserId() == null) {
                throw new ServiceException("创意组中广告主id不能为空");
            }
            if (ObjectUtils.isEmpty(groupQo.getVideoMaterialList()) || groupQo.getVideoMaterialList().size() == 0) {
                throw new ServiceException("至少上传一个创意组");
            }
            for (PromotionCreateV30RequestPromotionMaterialsVideoMaterialListInner material : groupQo.getVideoMaterialList()) {
                if (ObjectUtils.isEmpty(material.getVideoId())) {
                    throw new ServiceException("创意组视频id不能为空");
                }
                if (ObjectUtils.isEmpty(material.getVideoCoverId())) {
                    throw new ServiceException("创意组视频封面图片ID不能为空");
                }
                if (ObjectUtils.isEmpty(material.getImageMode())) {
                    throw new ServiceException("创意组素材类型不能为空");
                }
            }
        }

        this.microPromotionType = this.project.getMicroPromotionType().getValue();
        if (ProjectCreateV30MicroPromotionType.WECHAT_APP.equals(this.project.getMicroPromotionType())) {
            this.project.getDeliverySetting().setDeepBidType(null);//微信没有深度优化方式
//            if(this.getAnchorMaterialList()==null || this.getAnchorMaterialList().size()==0){
//                throw new ServiceException("微小原生锚点不能为空");
//            }
            if (this.getProject().getOptimizeGoal().getExternalAction() == null) {
                throw new ServiceException("项目信息-优化目标不能为空");
            }

        } else if (ProjectCreateV30MicroPromotionType.BYTE_APP.equals(this.project.getMicroPromotionType())) {
            if (this.getProject().getOptimizeGoal().getExternalAction() == null) {
                throw new ServiceException("项目信息-优化目标不能为空");
            } else {
                if (this.getProject().getOptimizeGoal().getExternalAction().equals(ProjectCreateV30OptimizeGoalExternalAction.TYPE_GAME_ADDICTION)) {
                    this.project.getDeliverySetting().setDeepBidType(null);
                }
            }
            if (ObjectUtils.isEmpty(this.urls) || this.urls.size() == 0) {
                throw new ServiceException("请填写字节小程序链接");
            }
            for (CreatePromotionUrlQo url : this.urls) {
                if (ObjectUtils.isEmpty(url.getAdvertiserId())) {
                    throw new ServiceException("字节小程序链接urls信息不全");
                }
                if (ObjectUtils.isEmpty(url.getUrl()) && (ObjectUtils.isEmpty(url.getAppId()) || ObjectUtils.isEmpty(url.getStartPath()) || ObjectUtils.isEmpty(url.getParams()))) {
                    throw new ServiceException("字节小程序调起链接(url和app_id、start_path、params必须传一个，用于自动生成小程序链接)");
                }
            }
        } else if (ProjectCreateV30MicroPromotionType.AWEME.equals(this.project.getMicroPromotionType())) {
            //抖音号是固定参数，防止前端传错，后端直接写死
            this.project.getOptimizeGoal().setExternalAction(ProjectCreateV30OptimizeGoalExternalAction.TYPE_ACTIVE);
            this.project.getOptimizeGoal().setDeepExternalAction(ProjectCreateV30OptimizeGoalDeepExternalAction.TYPE_LT_ROI);
        }

        PromotionCreateV30RequestPromotionMaterialsProductInfo productInfo = this.promotion.getPromotionMaterials().getProductInfo();
        if (productInfo == null) {
            throw new ServiceException("产品信息不全");
        }
        if (ObjectUtils.isEmpty(productInfo.getTitles()) || productInfo.getTitles().size() == 0 || productInfo.getTitles().size() != 1 || productInfo.getTitles().get(0) == null || productInfo.getTitles().get(0).length() > 20) {
            throw new ServiceException("产品名称不能为空，字数限制：[1-20]，数组上限为1");
        }
        if (productInfo.getImageIds() == null || productInfo.getImageIds().size() == 0) {
            throw new ServiceException("请上传产品主图");
        }
        if (productInfo.getSellingPoints() == null || productInfo.getSellingPoints().size() == 0) {
            throw new ServiceException("产品卖点，字数限制：[6-9]，数组上限为10");
        }


    }

    /**
     * 微信小程序
     *
     * @return
     */
    public boolean isWechat() {
        return ProjectCreateV30MicroPromotionType.WECHAT_APP.equals(this.project.getMicroPromotionType());
    }

    /**
     * 字节小程序
     *
     * @return
     */
    public boolean isByte() {
        return ProjectCreateV30MicroPromotionType.BYTE_APP.equals(this.project.getMicroPromotionType());
    }

    /**
     * 抖音号
     *
     * @return
     */
    public boolean isDouYinHao() {
        return ProjectCreateV30MicroPromotionType.AWEME.equals(this.project.getMicroPromotionType());
    }


}
